<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>完整流程测试 - 登录和地址管理</title>
    <script src="js/vue-2.5.16.js"></script>
    <script src="js/axios-0.18.0.min.js"></script>
    <script src="js/host.js"></script>
    <script src="js/common.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
        }

        .section {
            border: 1px solid #ddd;
            padding: 20px;
            margin: 20px 0;
            border-radius: 5px;
        }

        .login-form input,
        .address-form input,
        .address-form select {
            display: block;
            margin: 10px 0;
            padding: 8px;
            width: 300px;
        }

        button {
            padding: 10px 20px;
            margin: 5px;
            cursor: pointer;
        }

        .success {
            color: green;
        }

        .error {
            color: red;
        }

        .debug-info {
            background: #f5f5f5;
            padding: 10px;
            margin: 10px 0;
            border-left: 4px solid #007cba;
            font-family: monospace;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }

        .address-item {
            border: 1px solid #eee;
            padding: 10px;
            margin: 10px 0;
            border-radius: 3px;
            background: #fafafa;
        }

        .address-item strong {
            color: #333;
        }
    </style>
</head>

<body>
    <div id="app" class="container">
        <h1>美多商城 - 完整流程测试</h1>

        <!-- 登录部分 -->
        <div class="section">
            <h2>1. 用户登录</h2>
            <div class="login-form">
                <input type="text" v-model="loginForm.username" placeholder="用户名/手机号">
                <input type="password" v-model="loginForm.password" placeholder="密码">
                <button @click="login" :disabled="loginLoading">
                    {{ loginLoading ? '登录中...' : '登录' }}
                </button>
            </div>
            <div :class="loginResult.success ? 'success' : 'error'" v-if="loginResult.message">
                {{ loginResult.message }}
            </div>
            <div class="debug-info" v-if="loginDebug">{{ loginDebug }}</div>
        </div>

        <!-- 地址列表 -->
        <div class="section" v-if="isLoggedIn">
            <h2>2. 地址列表</h2>
            <button @click="getAddresses" :disabled="addressLoading">
                {{ addressLoading ? '获取中...' : '刷新地址列表' }}
            </button>
            <div v-if="addresses.length > 0">
                <div v-for="(address, index) in addresses" :key="address.id" class="address-item">
                    <strong>{{ address.title }}</strong> - {{ address.receiver }}<br>
                    手机号: {{ address.mobile }}<br>
                    固定电话: {{ address.tel || '无' }}<br>
                    地址: {{ address.province }} {{ address.city }} {{ address.district }} {{ address.place }}<br>
                    邮箱: {{ address.email || '无' }}<br>
                    <button @click="editAddress(index)">编辑</button>
                    <button @click="deleteAddress(index)">删除</button>
                </div>
            </div>
            <div v-else>暂无地址</div>
            <div class="debug-info" v-if="addressDebug">{{ addressDebug }}</div>
        </div>

        <!-- 添加/编辑地址 -->
        <div class="section" v-if="isLoggedIn">
            <h2>3. {{ editingIndex === -1 ? '添加新地址' : '编辑地址' }}</h2>
            <div class="address-form">
                <input type="text" v-model="addressForm.receiver" placeholder="收货人姓名">
                <select v-model="addressForm.province_id" @change="getCities">
                    <option value="">请选择省份</option>
                    <option v-for="province in provinces" :value="province.id">{{ province.name }}</option>
                </select>
                <select v-model="addressForm.city_id" @change="getDistricts" :disabled="!cities.length">
                    <option value="">请选择城市</option>
                    <option v-for="city in cities" :value="city.id">{{ city.name }}</option>
                </select>
                <select v-model="addressForm.district_id" :disabled="!districts.length">
                    <option value="">请选择区县</option>
                    <option v-for="district in districts" :value="district.id">{{ district.name }}</option>
                </select>
                <input type="text" v-model="addressForm.place" placeholder="详细地址">
                <input type="text" v-model="addressForm.mobile" placeholder="手机号">
                <input type="text" v-model="addressForm.tel" placeholder="固定电话（可选）">
                <input type="text" v-model="addressForm.email" placeholder="邮箱（可选）">
                <button @click="saveAddress" :disabled="saveLoading">
                    {{ saveLoading ? '保存中...' : '保存地址' }}
                </button>
                <button @click="resetForm" type="button">重置表单</button>
            </div>
            <div :class="saveResult.success ? 'success' : 'error'" v-if="saveResult.message">
                {{ saveResult.message }}
            </div>
            <div class="debug-info" v-if="saveDebug">{{ saveDebug }}</div>
        </div>
    </div>

    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                host: host,
                isLoggedIn: false,
                loginLoading: false,
                addressLoading: false,
                saveLoading: false,
                loginForm: {
                    username: 'itcast_01',
                    password: '12345678'
                },
                loginResult: { success: false, message: '' },
                loginDebug: '',
                addresses: [],
                provinces: [],
                cities: [],
                districts: [],
                addressDebug: '',
                addressForm: {
                    receiver: '',
                    province_id: '',
                    city_id: '',
                    district_id: '',
                    place: '',
                    mobile: '',
                    tel: '',
                    email: ''
                },
                editingIndex: -1,
                saveResult: { success: false, message: '' },
                saveDebug: ''
            },
            mounted: function () {
                this.debugLog('应用初始化完成，host: ' + this.host);
            },
            methods: {
                debugLog: function (message) {
                    const timestamp = new Date().toLocaleTimeString();
                    this.saveDebug += `[${timestamp}] ${message}\n`;
                    console.log(`[${timestamp}]`, message);
                },

                login: function () {
                    this.loginLoading = true;
                    this.loginDebug = '';
                    this.debugLog('开始登录操作');

                    var url = this.host + '/login/';
                    this.debugLog('登录URL: ' + url);
                    this.debugLog('登录数据: ' + JSON.stringify(this.loginForm));

                    axios.post(url, this.loginForm, {
                        responseType: 'json',
                        withCredentials: true,
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                        .then(response => {
                            this.debugLog('登录响应: ' + JSON.stringify(response.data));
                            if (response.data && response.data.code === 0) {
                                this.isLoggedIn = true;
                                this.loginResult = { success: true, message: '登录成功！' };
                                this.getProvinces();
                                this.getAddresses();
                            } else {
                                this.loginResult = { success: false, message: '登录失败: ' + (response.data.errmsg || '未知错误') };
                            }
                        })
                        .catch(error => {
                            this.debugLog('登录错误: ' + JSON.stringify({
                                message: error.message,
                                response: error.response ? error.response.data : '无响应',
                                status: error.response ? error.response.status : '无状态'
                            }));
                            this.loginResult = { success: false, message: '网络错误，请检查控制台日志' };
                        })
                        .finally(() => {
                            this.loginLoading = false;
                        });
                },

                getProvinces: function () {
                    var url = this.host + '/areas/';
                    this.debugLog('获取省份URL: ' + url);

                    axios.get(url, {
                        responseType: 'json',
                        withCredentials: true
                    })
                        .then(response => {
                            this.debugLog('省份响应: ' + JSON.stringify(response.data));
                            if (response.data && response.data.province_list) {
                                this.provinces = response.data.province_list;
                            }
                        })
                        .catch(error => {
                            this.debugLog('获取省份错误: ' + JSON.stringify(error.response ? error.response.data : '无响应'));
                        });
                },

                getCities: function () {
                    if (!this.addressForm.province_id) return;

                    var url = this.host + '/areas/' + this.addressForm.province_id + '/';
                    this.debugLog('获取城市URL: ' + url);

                    axios.get(url, {
                        responseType: 'json',
                        withCredentials: true
                    })
                        .then(response => {
                            this.debugLog('城市响应: ' + JSON.stringify(response.data));
                            if (response.data && response.data.sub_data && response.data.sub_data.subs) {
                                this.cities = response.data.sub_data.subs;
                                this.districts = [];
                                this.addressForm.city_id = '';
                                this.addressForm.district_id = '';
                            }
                        })
                        .catch(error => {
                            this.debugLog('获取城市错误: ' + JSON.stringify(error.response ? error.response.data : '无响应'));
                        });
                },

                getDistricts: function () {
                    if (!this.addressForm.city_id) return;

                    var url = this.host + '/areas/' + this.addressForm.city_id + '/';
                    this.debugLog('获取区县URL: ' + url);

                    axios.get(url, {
                        responseType: 'json',
                        withCredentials: true
                    })
                        .then(response => {
                            this.debugLog('区县响应: ' + JSON.stringify(response.data));
                            if (response.data && response.data.sub_data && response.data.sub_data.subs) {
                                this.districts = response.data.sub_data.subs;
                                this.addressForm.district_id = '';
                            }
                        })
                        .catch(error => {
                            this.debugLog('获取区县错误: ' + JSON.stringify(error.response ? error.response.data : '无响应'));
                        });
                },

                getAddresses: function () {
                    this.addressLoading = true;
                    this.addressDebug = '';

                    var url = this.host + '/addresses/';
                    this.debugLog('获取地址URL: ' + url);

                    axios.get(url, {
                        responseType: 'json',
                        withCredentials: true
                    })
                        .then(response => {
                            this.addressDebug = '地址响应: ' + JSON.stringify(response.data, null, 2);
                            if (response.data && Array.isArray(response.data.addresses)) {
                                this.addresses = response.data.addresses;
                                this.debugLog('成功获取 ' + this.addresses.length + ' 个地址');
                            }
                        })
                        .catch(error => {
                            this.addressDebug = '获取地址错误: ' + JSON.stringify(error.response ? error.response.data : '无响应', null, 2);
                            this.debugLog('获取地址失败');
                        })
                        .finally(() => {
                            this.addressLoading = false;
                        });
                },

                saveAddress: function () {
                    this.saveLoading = true;
                    this.saveDebug = '';
                    this.saveResult = { success: false, message: '' };

                    // 验证必填字段
                    if (!this.addressForm.receiver || !this.addressForm.place || !this.addressForm.mobile ||
                        !this.addressForm.province_id || !this.addressForm.city_id || !this.addressForm.district_id) {
                        this.saveResult = { success: false, message: '请填写所有必填字段' };
                        this.saveLoading = false;
                        return;
                    }

                    // 创建纯数据对象
                    var addressData = JSON.parse(JSON.stringify({
                        receiver: this.addressForm.receiver,
                        province_id: this.addressForm.province_id,
                        city_id: this.addressForm.city_id,
                        district_id: this.addressForm.district_id,
                        place: this.addressForm.place,
                        mobile: this.addressForm.mobile,
                        tel: this.addressForm.tel,
                        email: this.addressForm.email,
                        title: this.addressForm.receiver
                    }));

                    this.debugLog('准备保存地址数据: ' + JSON.stringify(addressData));
                    this.debugLog('tel字段类型: ' + typeof addressData.tel);
                    this.debugLog('tel字段值: ' + addressData.tel);

                    var isEdit = this.editingIndex !== -1;
                    var url, method;

                    if (isEdit) {
                        var addressId = this.addresses[this.editingIndex].id;
                        url = this.host + '/addresses/' + addressId + '/';
                        method = 'PUT';
                        this.debugLog('编辑地址，ID: ' + addressId);
                    } else {
                        url = this.host + '/addresses/create/';
                        method = 'POST';
                        this.debugLog('新增地址');
                    }

                    this.debugLog('请求URL: ' + url + ', 方法: ' + method);

                    axios({
                        method: method,
                        url: url,
                        data: addressData,
                        responseType: 'json',
                        withCredentials: true,
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                        .then(response => {
                            this.debugLog('保存地址响应: ' + JSON.stringify(response.data));
                            if (response.data.code === 0) {
                                this.saveResult = { success: true, message: '地址保存成功！' };
                                this.resetForm();
                                this.getAddresses();
                            } else {
                                this.saveResult = { success: false, message: '保存失败: ' + (response.data.errmsg || '未知错误') };
                            }
                        })
                        .catch(error => {
                            this.debugLog('保存地址错误: ' + JSON.stringify({
                                message: error.message,
                                response: error.response ? error.response.data : '无响应',
                                status: error.response ? error.response.status : '无状态'
                            }));
                            this.saveResult = { success: false, message: '网络错误，请检查控制台日志' };
                        })
                        .finally(() => {
                            this.saveLoading = false;
                        });
                },

                editAddress: function (index) {
                    var address = this.addresses[index];
                    this.debugLog('编辑地址: ' + JSON.stringify(address));

                    this.addressForm = JSON.parse(JSON.stringify({
                        receiver: address.receiver,
                        province_id: '',
                        city_id: '',
                        district_id: '',
                        place: address.place,
                        mobile: address.mobile,
                        tel: address.tel,
                        email: address.email
                    }));

                    this.editingIndex = index;
                    this.cities = [];
                    this.districts = [];

                    // 设置省市区
                    var self = this;
                    setTimeout(function () {
                        self.addressForm.province_id = address.province_id || '';
                        self.getCities();
                        setTimeout(function () {
                            self.addressForm.city_id = address.city_id || '';
                            self.getDistricts();
                            setTimeout(function () {
                                self.addressForm.district_id = address.district_id || '';
                            }, 100);
                        }, 100);
                    }, 100);
                },

                deleteAddress: function (index) {
                    if (!confirm('确定要删除这个地址吗？')) return;

                    var address = this.addresses[index];
                    var url = this.host + '/addresses/' + address.id + '/';
                    this.debugLog('删除地址URL: ' + url);

                    axios.delete(url, {
                        responseType: 'json',
                        withCredentials: true
                    })
                        .then(response => {
                            this.debugLog('删除地址响应: ' + JSON.stringify(response.data));
                            if (response.data.code === 0) {
                                this.addresses.splice(index, 1);
                                this.debugLog('地址删除成功');
                            }
                        })
                        .catch(error => {
                            this.debugLog('删除地址错误: ' + JSON.stringify(error.response ? error.response.data : '无响应'));
                        });
                },

                resetForm: function () {
                    this.addressForm = {
                        receiver: '',
                        province_id: '',
                        city_id: '',
                        district_id: '',
                        place: '',
                        mobile: '',
                        tel: '',
                        email: ''
                    };
                    this.editingIndex = -1;
                    this.cities = [];
                    this.districts = [];
                }
            }
        });
    </script>
</body>

</html>